package cn.parllay.dingdangproject.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.parllay.dingdangproject.DingDangApplication;
import cn.parllay.dingdangproject.R;
import cn.parllay.dingdangproject.bean.login.Account;
import cn.parllay.dingdangproject.bean.login.Employee;
import cn.parllay.dingdangproject.bean.login.LoginParams;
import cn.parllay.dingdangproject.bean.login.LoginResult;
import cn.parllay.dingdangproject.global.DingStoreAPI;
import cn.parllay.dingdangproject.global.ScreenInfo;
import cn.parllay.dingdangproject.utils.LoadingTools;
import cn.parllay.dingdangproject.utils.MD5Encoder;
import cn.parllay.dingdangproject.utils.NetWorkUtils;
import cn.parllay.dingdangproject.utils.ScrollByKeyboard;
import cn.parllay.dingdangproject.utils.SpUtils;
import cn.parllay.dingdangproject.utils.ToastUtils;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.text_input_phone)
    EditText text_input_mobile;

    @BindView(R.id.text_input_password)
    EditText text_input_password;

    @BindView(R.id.btn_login)
    Button btn_login;

    @BindView(R.id.ll_loginView)
    LinearLayout ll_loginView;

    private String md5Password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        ButterKnife.bind(this);

        int width = ScreenInfo.getInstance().getWidth();
        int height = ScreenInfo.getInstance().getHeight();
        Log.e("TAG", "width == " + width);
        Log.e("TAG", "height == " + height);

        ScrollByKeyboard.autoScrollView(ll_loginView, btn_login);//弹出软键盘时滚动视图

        String mobile = SpUtils.getInstance(LoginActivity.this).getString(SpUtils.MOBILE, "");
        text_input_mobile.setText(mobile);

        initListener();

        toMainOrLogin();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

       releaseSource();

    }

    @OnClick(R.id.btn_login)
    void onLoginClick(){
        login();
    }

    private void toMainOrLogin() {

        //判断是否登录过
        boolean isLogin = SpUtils.getInstance(this).getBoolean(SpUtils.IS_LOGIN, false);
        if (isLogin) {
            // 主页面
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();

        }
    }

    private void initListener() {
        //密码输入监听
        text_input_password.addTextChangedListener(textWatcher);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            //校验输入密码的长度
            checkPassword(s.toString());
        }
    };

    //校验密码长度
    private void checkPassword(String password) {
        if (password.length() >= 3) {
            btn_login.setBackgroundColor(getResources().getColor(R.color.blue1));
            btn_login.setClickable(true);

        } else {
            btn_login.setBackgroundColor(getResources().getColor(R.color.grey2));
            btn_login.setClickable(false);
        }
    }

    // 登录方法
    private void login() {
        // 获取用户名和密码
        final String mobile = text_input_mobile.getText().toString();
        final String password = text_input_password.getText().toString();

        // 校验
        if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(password)) {
            // 提示
            ToastUtils.showToast("用户名或密码不能为空");
            // 返回
            return;
        }

        // 显示进度条
        LoadingTools.getInstance().showLoading(this,"登录中...");
        // 去服务器验证用户名和密码

        NetWorkUtils.doPostJson(DingStoreAPI.login(), getLoginParams(),LoginResult.class,loginCallback);
    }

    private NetWorkUtils.OnRequestListener loginCallback = new NetWorkUtils.OnRequestListener<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

            String code = loginResult.getCode();
            if ("0".equals(code)) {
                //保存用户信息到本地
                saveUserInfoToLocal(loginResult);

                // 登录成功 跳转到主页面
                MainActivity.actionStart(LoginActivity.this);

                finish();

            } else {
                ToastUtils.showToast("登录失败:" + loginResult.getMessage());
            }

            LoadingTools.getInstance().cancelLoading();
        }

        @Override
        public void onError(String errorMsg) {
            Log.e("TAG", errorMsg);
        }
    };

    private void saveUserInfoToLocal(LoginResult loginResult) {

        Employee employee = loginResult.getData();
        if(employee == null) {
            return;
        }
        //保存已登录状态
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.IS_LOGIN, true);
        //保存登录的手机号码
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.MOBILE, employee.getMobile());
        //保存密码到本地
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.PASS_WORD,employee.getPassword());
        //保存昵称到本地
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.NICK_NAME,employee.getEmployeName());
        //保存登录的userId
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.USER_ID, employee.getEmployeId());
        //保存门店ID到本地
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.STORE_ID, employee.getStoreId());
        //保存门店名称到本地
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.STORE_NAME, employee.getStoreName());
        //保存角色
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.ROLE, employee.getRoleId());
        //保存门店storeNo
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.STORE_NO, employee.getStoreNo());
        //保存公司ID
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.COMPANYI_ID, employee.getCompanyId());
        //保存门店状态
        SpUtils.getInstance(DingDangApplication.getContext()).save(SpUtils.LINE_STATUS, employee.getLineStatus());
    }

    private void releaseSource(){
        if(textWatcher != null) {
            textWatcher = null;
        }
        if(loginCallback != null) {
            loginCallback = null;
        }
    }

    private LoginParams getLoginParams(){
        LoginParams loginParams = new LoginParams();
        Account account = new Account();
        account.setMobile(text_input_mobile.getText().toString());
        String password = text_input_password.getText().toString();
        try {
            md5Password = MD5Encoder.encode(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        account.setPassword(md5Password);
        loginParams.setData(account);
        return loginParams;
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

}
